var express = require('express');
var router = express.Router();
var { user, house, housedetail, comment, hshop } = require('../../model/model');
// const key = 'five_612_apitokenkey'
const SMSClient = require('@alicloud/sms-sdk')
// const jwt = require('jsonwebtoken')
/* GET home page. */
router.post('/adduser', async(req, res) => {
  const existingUser = await user.findOne({ phone: req.body.phone },{username:req.body.username}); // 查找已有电话号码的用户
  if (existingUser) {
    return res.status(400).json({ code: 400, msg: '此电话号码已被注册' });
  }
  user.create(req.body)
  res.send({
    code: 200,
    msg: '添加成功'
  })
  
})

// 修改用户信息、
router.put('/updateuser', async (req, res) => {
  await user.updateOne({ phone: req.body.phone}, {password: req.body.password})
  console.log(req.body);
  res.send({
    code: 200,
    msg: '修改成功'
  })
});


router.get('/login', async (req, res) => {
  let data = await user.find({ phone: req.query.phone, password: req.query.password })
  console.log(req.query);

  if (data.length > 0) {
    res.send({
      code: 200,
      msg: '登录成功',
      data
    })
  } else {
    res.send({
      code: 201,
      msg: '账号或密码错误',
    })
  }
})

router.post('/addhouse', (req, res) => {
  house.create(req.body)
  res.send({
    code: 200,
    msg: '添加成功'
  })
})

router.get('/house', async (req, res) => {
  let data = await house.find()
  res.send({
    code: 200,
    msg: '获取成功',
    data
  })
})

// 添加评论
router.post('/addcomment', (req, res) => {
  comment.create(req.body)
  res.send({
    code: 200,
    msg: '添加成功'
  })
})

// 获取评论
router.get('/comment', async (req, res) => {
  let id = req.query.id
  try {
    let data = await comment.find({ hid: id }).populate('hid')
    res.send({
      code: 200,
      msg: '获取成功',
      data
    })
  } catch (err) {
    res.send({
      code: 201,
      msg: '获取失败',
      err
    })
  }
})

// 获取民宿详情
router.get(`/houseinfo`, async (req, res) => {
  const id = req.query.id

  try {
    let data = await housedetail.find({ hid: id }).populate('hid')
    res.send({
      code: 200,
      msg: '获取成功',
      data
    })
  } catch (err) {
    res.status(500).send({
      code: 500,
      msg: '获取失败',
      err: err.message
    })
  }
})

// 添加民宿详情
router.post('/addhouseinfo', (req, res) => {
  housedetail.create(req.body)
  res.send({
    code: 200,
    msg: '添加成功'
  })
})

// 添加民宿订单
router.post('/addhshop', (req, res) => {
  hshop.create(req.body)
  res.send({
    code: 200,
    msg: '添加成功'
  })
})

// 获取民宿订单
router.get('/gethshop', async (req, res) => {
  let data = await hshop.find().populate('hid')
  res.send({
    code: 200,
    msg: '获取成功',
    data
  })
})

router.get('/sendsms', function (req, res, next) {
	if (req.query.phoneNumber) {
		const phoneNum = req.query.phoneNumber;
		const accessKeyId = 'LTAI5tFxoyrsCchtxziWdufs'; //在用户信息管理中可以看到
		const secretAccessKey = 'rPqLxbyTpQvqFwr88JGkyrzUJLyL5a'; // 在用户信息管理中可以看到

    // const accessKeyId = 'LTAI5tF2syxeE5xeh9L6jA1r'; //在用户信息管理中可以看到
		// const secretAccessKey = 'zCsIndBqYgy3Lqs7ZBfxVuyZFrr2D4'; // 在用户信息管理中可以看到

		//初始化sms_client
		let smsClient = new SMSClient({ accessKeyId, secretAccessKey });

		const scode = Math.floor(Math.random() * 9000 + 1000) //生成随机验证码
    console.log(scode,'ffffffffffffffffffffffff');
    
		// 发送短信
		// 开始发送短信
		smsClient.sendSMS({
			PhoneNumbers: phoneNum, // 手机号
			SignName: "alTeng0916", //签名管理中
			TemplateCode: "SMS_302670814", //在模板管理中
			TemplateParam: '{"code":' + scode + '}', //短信模板变量对应的实际值，JSON格式
		})
			.then(result => {
				let { Code } = result;
				if (Code == 'OK') {
					// 短信发送成功
					res.send({
						code: 200,
						data: result,
						scode: scode
					})
				}
			})
			.catch(err => {
				res.send({
					msg: "fail"
				})
			})
	} else {
		return res.send({
			msg: '未获取到用户信息'
		})
	}
	// next();
});

// 发送验证码
router.post('/send-code', async (req, res) => {
  const { phoneNumber } = req.body;

  if (!phoneNumber) {
    return res.status(400).json({ error: '手机号不能为空' });
  }

  // 模拟生成验证码
  const code = Math.floor(100000 + Math.random() * 900000);

  // 存储验证码（这里可以使用缓存如Redis）
  const verificationCodes = {};
  verificationCodes[phoneNumber] = code;

  // 模拟发送验证码到手机
  console.log(`验证码已发送到 ${phoneNumber}: ${code}`);
  // 这里可以调用真实的短信发送服务，例如阿里云、腾讯云等
  // 示例：
  // const response = await axios.post('https://sms.api.example.com/send', {
  //   phoneNumber,
  //   code
  // });

  res.json({ success: true, message: '验证码已发送，请查收短信' });
});

// 验证验证码
router.post('/verify-code', async (req, res) => {
  const { phoneNumber, code } = req.body;

  if (!phoneNumber || !code) {
    return res.status(400).json({ error: '手机号或验证码不能为空' });
  }

  const storedCode = verificationCodes[phoneNumber];

  if (storedCode === undefined) {
    return res.status(400).json({ error: '该手机号未请求过验证码' });
  }

  if (storedCode.toString() !== code) {
    return res.status(400).json({ error: '验证码错误' });
  }

  delete verificationCodes[phoneNumber];
  res.json({ success: true, message: '验证码验证成功' });
});

module.exports = router;